=head1 NAME

EPrints::Plugin::Export::EPub

=cut

package EPrints::Plugin::Export::EPub;

use EPrints::Plugin::Export::XMLFile;
our @ISA = qw( EPrints::Plugin::Export );

use strict;
use Data::Dumper;
use EBook::EPUB;
use File::Basename;

sub new
{
        my( $class, %opts ) = @_;

        my( $self ) = $class->SUPER::new( %opts );

        $self->{name} = "EPub";
        $self->{accept} = [ 'list/eprint' ];
        #NB: 'dataobj/shelf' this one is not needed as exportshlef will pass a list to the plugin anyways...
        
        $self->{advertise} = 1;
        $self->{suffix} = ".epub";
        $self->{mimetype} = "application/zip";
        $self->{shelf} = $opts{shelf}; #that's not ripe for a mistype?
        
        return $self;
}

sub output_list
{
        my( $plugin, %opts ) = @_;


	# Create EPUB object
	my $epub = EBook::EPUB->new;
	
	# Parameters
	my $convert = $plugin->{repository}->get_conf( "executables" )->{'convert'};
	my $geom = $plugin->param('images_geom');

	#shelf data (if available)
	my $antho_title = "Anthologized  Xperiment";
	my $author = EPrints::XML::to_string($plugin->{session}->current_user->render_description());
	my $lang = "en";
	my $rights;
	if(defined $plugin->{shelf}){
		my $shelf = $plugin->{shelf};
		$antho_title = 	$shelf->{data}->{title};
		
		#TODO get author that is shelf owner, but maybe not current_user
		#TODO (not here) analyse document languages to decide on a "main" language for the ebook
		#TODO get rights statement from repository-scale IPR... or use most restrictive document license

	}

	# Set metadata: title/author/language/id
	$epub->add_title($antho_title);
	$epub->add_author($author);
	$epub->add_language($lang);
	$epub->add_rights($rights) if(defined $rights);

	$epub->add_format("application/epub+zip");

#	$epub->add_identifier('012345678', 'ISBN');
#	my $rights = "Crown Copyright:\nImages supplied by The National Archives are free to use for research and study. No commercial use may be made of them without the prior permission of The National Archives Image Library. Contact: image-library\@nationalarchives.gov.uk";

	# Add package content: stylesheet, font, xhtml and cover
	#TODO?? from anthologizr config css for different (default) layouts
	#$epub->copy_stylesheet('./ebook_src/auto.css', 'auto.css');
#	$epub->copy_stylesheet('./ebook_src/summary_page_iframe.css', 'summary_page_iframe.css');

#	# Add cover image
#	# Not actual epub standart but does the trick for iBooks
	#TODO IF first documnt is an image, use that as coverpage. (config option)
	# ELSE create a coverpage from shelf metadata (a la EPrints coverpage plugin)
	#	eg Shelf title, shelf description "compiled by shelf owner" from repository name

#	my $cover_id = $epub->copy_image('./ebook_src/WWII_cover.PNG', 'WWII_cover.PNG');
#	$epub->add_meta_item('cover', $cover_id);
        
	my $type = $opts{list}->get_dataset->confid;
	my $xml = $plugin->{repository}->xml; 



	#print STDERR $opts{list}->count."\n";

	#loop through items creating content references
	my @chapters;
  $opts{list}->map( sub {
              my( $session, $dataset, $item ) = @_;
  	# Using main file of first doc from each item in the shelf
  	#TODO use main file from all documents of the items in shelf
  	#TODO++ use supporting files (eg images) from documents
  
  	##but for now....
  	my $first_doc = ($item->get_all_documents())[0];
  	my $main_file = $first_doc->get_stored_file( $first_doc->get_main );
  	my $content_addr = $main_file->get_local_copy;	
  
  	#TODO analyse mimetype of file and act accordingly
  	#IF xhtml, (maybe html) or image do below
  	#ELSIF application/pdf run through pdf2html 
  	#ELSIF application/"doc" run through doc2html
  	#ELSIF text/plain wrap in xhtml (with nice default css)
  	#ELSE gawd elp us
  	
  	my $mime_type = $main_file->get_value("mime_type");
  
    if ($mime_type =~ /image/) {
      # images
      
      print STDERR "EPUB: image detected\n";
      
      my $filename = fileparse($content_addr);
      my $dst = $epub->tmpdir."/$filename";
      my @convert_args = ($convert, "-strip", "-colorspace", "RGB", "-background", "white", "-resize","$geom>", "$content_addr", "JPEG:$dst");
      
      my $rc = system(@convert_args);
	    if (!$rc) {
        print STDERR "ERROR converting image for ebook: " . join(", ", @convert_args);
      }
      
      $epub->copy_file($dst, $filename, 'image/jpg');
      
      # we'd need an image template container
      my $image_template_text = "<html>";
      $image_template_text .= "<head>";
      $image_template_text .= "<title>".$item->value("title")."</title>";
      #$image_template_text .= "<link rel="stylesheet" type="text/css" href="/style/summary_page_iframe.css">";
      $image_template_text .= "</head>";
      $image_template_text .= "<body>";
      $image_template_text .= "<img src=\"".$filename."\" />";
      $image_template_text .= "</body></html>";
      
      my $image_xhtml = $epub->tmpdir."/page_1.xhtml";
      
      open (PAGE, ">>".$image_xhtml);
      print PAGE $image_template_text;
      close (PAGE);

      push @chapters, {"path"  => $image_xhtml, "label" => $item->value("title")};

    }
    else {
      # raw content
      #			print STDERR "content_addr: ".$content_addr."\n";
  	  push @chapters, {"path"  => $content_addr, "label" => $item->value("title")};
    }
  
  #           },
  } );
  
	#loop through references copying the content and creating navpoints
	my $navpoint;
	my $chapter_counter = 1;
	for my $chapter(@chapters){
		my $chapter_id = $epub->copy_xhtml($chapter->{path}, basename($chapter->{path}) );
		$navpoint = $epub->add_navpoint(
			label       => $chapter->{label},
			id          => $chapter_id,
			content     => basename($chapter->{path}),
			play_order  => $chapter_counter # should always start with 1
		);
		$chapter_counter++;
	}

	#Make the epub...
	my $the_book = $epub->tmpdir."/".EPrints::Utils::escape_filename($antho_title).".epub";
	$epub->pack_zip($the_book);
	#if you want to see a working epub check the logs...
	print STDERR "Created epub at $the_book\n";

	my $r = "";
        open(my $tmpfile, "<", "$the_book") or die "$the_book: $!";
        binmode($tmpfile);

        my $f = $opts{fh} ?
                sub { print {$opts{fh}} $_[0] } :
                sub { $r .= $_[0] };

	binmode($opts{fh});
        while(sysread($tmpfile, my $buffer, 1024))
        {
                &$f( $buffer );
        }

	exit;
        return $r
}

